import requests
import json
from DrissionPage import SessionPage, ChromiumOptions, SessionOptions, Chromium
from DrissionPage.common import Keys

DETAIL_URL = "https://ad.xiaohongshu.com/api/leona/rtb/unit/detail"
headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9",
    "content-type": "application/json",
    "origin": "https://ad.xiaohongshu.com",
    "priority": "u=1, i",
    "referer": "https://ad.xiaohongshu.com/aurora/ad/edit/creativity/127506399/296939925/1783799772/4/1/2?from=manage&manageLevel=byAccount&AFormGrayFlag=false&vSellerId=66da9a60a6e9d100165983cc",
    "sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36",
    "v-seller-id": "66da9a60a6e9d100165983cc",
    "x-b3-traceid": "f829846b35c7d38a"
    # "x-s-common": "2UQAPsHC+aIjqArjwjHjNsQhPsHCH0rjNsQhPaHCH0c1PahFHjIj2eHjwjQgynEDJ74AHjIj2ePjwjQY4gQ6qfrTq9YSJBIjNsQh+sHCH0H1Pshl+0DjNsQh+aHCH0rE+0mSPfb08nGF8gGIP0mY8BQlGf4h8B+IqAWhqBYj4nTCGnQ1Gnkf+/ZIPeZU+AHUweZjNsQh+jHCHjHVHdW7H0ijHjIj2eWjwjQQPAYUaBzdq9k6qB4Q4fpA8b878FSet9RQzLlTcSiM8/+n4MYP8F8LagY/P9Ql4FpUzfpS2BcI8nT1GFbC/L88JdbFyrSiafp/8DMra7pFLDDAa7+8J7QgabmFz7Qjp0mcwp4fanD68p40+fp8qgzELLbILrDA+9p3JpH9LLI3+LSk+d+DJfRSL98lnLYl49IUqgcMc0mrJFShtMmozB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bl4MbUpd4kaLpd8gYD4LSQyFIM89hA8nzn4opsLozQcDS0LnFEzMzQyMzVN7p7prS3/7+kJsTPanSCqoQc49zQy/YgqMmFJo+c4okQyBYfagGhpFSipbm64g4ianSrNFSbad+fqg4L8LDFnrSiaLEQz/pApB49qM+M4UTQ40zranYMzn4T/bzQc7QLN9+i+FS9Po+8/LRAPb87qDSbad+3LozHanYnwrS9a7PILochag8T8nRM4MYQzn4A8bkoJBEM4BV3pd4Sag8S8p+l4FQQyB4AzomV4LSi4d+gqBRAPpmFJpr6Po+gLoql8Lc6qA8M4bmQ2rbApBl98p+n4rYQyrlDanSTLBpn47+6p9F3agYd8n8n4FQccnRS2rD347QM4rEQPFMoanDAqM4+zgrjNsQhwaHCP/qU+0GAweLAPjIj2erIH0iINsQhP/rjwjQVygzSHdF="
}



material_cookies = {
    "a1": "1960e2acef4ev020adbqbgxdcps88phbukzabnajf50000272280",
    "webId": "4b6833e542f84e76fbfb34e006eddce8",
    "gid": "yjK8dJ0fS47WyjK8dJ0SdTI0i4dh8J80fDADuVikCfSUM028YYUxDD888JWJJY88jy8DJjDy",
    "customerClientId": "279177063808841",
    "abRequestId": "4b6833e542f84e76fbfb34e006eddce8",
    "x-user-id-fankui-out.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "x-user-id-partner.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "x-user-id-ad-market.xiaohongshu.com": "616fdd2b85d0b300016960dc",
    "access-token-ad-market.xiaohongshu.com": "customer.ad_market.AT-68c517519459434552924512enefn093ihp1uxmh",
    "webBuild": "4.70.2",
    "web_session": "040069b47b667a0c594b13eb563a4bf1a8fe62",
    "unread": "{%22ub%22:%22684949860000000022029f18%22%2C%22ue%22:%226855fee2000000002203c98c%22%2C%22uc%22:24}",
    "access-token-ad.xiaohongshu.com": "customer.leona.AT-68c517524241279341659602zyrexjtaejsfkjdq",
    "x-user-id-pgy.xiaohongshu.com": "64faeddd7500000000000010",
    "solar.beaker.session.id": "AT-68c517524973571265294417k5vbccqt5csrmpmq",
    "access-token-pgy.xiaohongshu.com": "customer.pgy.AT-68c517524973571265294417k5vbccqt5csrmpmq",
    "access-token-pgy.beta.xiaohongshu.com": "customer.pgy.AT-68c517524973571265294417k5vbccqt5csrmpmq",
    "customer-sso-sid": "68c5175256976512145576541m0npw3qgqxyo4ti",
    "ads-partner-sid": "07dd2c1667674c58b150c739171a7aaa",
    "system.alias": "ads_partner",
    "access-token-partner.xiaohongshu.com": "customer.ads_partner.AT-68c517525697651212086457hq1jmcwlli6vvhwx",
    "xsecappid": "aurora-shell",
    "websectiga": "f47eda31ec99545da40c2f731f0630efd2b0959e1dd10d5fedac3dce0bd1e04d",
    "sec_poison_id": "4f9c731d-673a-46e7-9ce4-e37e56c7cb0e",
    "ares.beaker.session.id": "1752214635033078037720",
    "acw_tc": "0a0d0ad817522148594875255eedbece5478a179e29a1a9f28707b5a78f2e0",
    "loadts": "1752214858562"
}

def open_account_palt_form(account_id, result_text=None):
    co = ChromiumOptions(read_file=False)  # 不读取文件方式新建配置对象
    so = SessionOptions(read_file=False)
    browser = Chromium(addr_or_opts=co, session_options=so)
    account_tab = browser.new_tab('https://partner.xiaohongshu.com/partner/subAccount-list')

    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').click()
    account_tab.ele('tag:input@@class=el-input__inner@@type=text@@autocomplete=off@@placeholder=请输入').input(account_id).input(Keys.ENTER)

    account_tab.wait(2)

    search_none_ele = account_tab.ele('tag:tr@@class=d-table__empty-row@@text()=暂无数据', timeout=0.5)
    if search_none_ele:
        return

    account_tab.ele('tag:span@@text():跳转', timeout=2).hover()
    jg_ele = account_tab.ele('tag:span@@class=d-text --color-static --color-current --size-text-paragraph d-text-nowrap d-text-ellipsis@@text():聚光平台', timeout=2)

    create_plan_tab = jg_ele.click.for_new_tab(by_js=True)
    create_plan_tab.wait.title_change("计划列表")
    unit_dict_cookie = create_plan_tab.cookies(all_info=False).as_dict()
    return unit_dict_cookie


def get_unit_detail(unit_id, account_id, unit_dict_cookie):
    """
    获取指定单元的原始数据
    :param account_id:
    :param unit_id: 单元ID
    :return: 原始数据 dict
    """
    headers['v-seller-id'] = account_id
    payload = {"id": unit_id}
    response = requests.post(DETAIL_URL, headers=headers, cookies=unit_dict_cookie, data=json.dumps(payload))

    if response.status_code == 200:
        return response.json().get('data', {})
    return {}


def transform_data(raw_data, mask_fill_status):
    # 将提取到的标题信息转化成编辑时候的数据格式
    title_fills = []
    for title_info in raw_data.get('titleInfoRespList', []):
        title_fills.append({
            "title": title_info['title'],
            "origin": title_info['origin'],
            "titleSource": title_info['titleSource'],
            "version": title_info['version']
        })

    # 提取图片信息
    mask_fills = []
    for photo_info in raw_data.get('photoInfoRespList', []):
        if mask_fill_status is not None:
            if mask_fill_status == '关闭':
                if photo_info.get('origin', False):
                    mask_fills.append({
                        "origin": photo_info['origin'],
                        "imageSource": photo_info['imageSource'],
                        "fileId": photo_info['fileId']
                    })
            else:
                mask_fills.append({
                    "origin": photo_info['origin'],
                    "imageSource": photo_info['imageSource'],
                    "fileId": photo_info['fileId']
                })
        else:
            mask_fills.append({
                "origin": photo_info['origin'],
                "imageSource": photo_info['imageSource'],
                "fileId": photo_info['fileId']
            })

    # 组合新数据
    return {
        "titleFills": title_fills,
        "maskFills": mask_fills
    }


def construct_edit_data(raw_data, title_fills, mask_fills):
    # 构建转换后的数据
    transformed_data = {
        "id": str(raw_data.get('creativityId', '')),
        "creativityName": raw_data.get('creativityName', ''),
        "clickUrls": raw_data.get('clickUrls', []),
        "expoUrls": [],
        "pretrialId": raw_data.get('pretrialId', ''),
        "barContent": raw_data.get('barContent', ''),
        "comment": raw_data.get('comment', ''),
        "commentUserList": raw_data.get('commentUserList', []),
        "intoShopParam": raw_data.get('intoShopParam', ''),
        "secondJumpPattern": '',
        "titleFills": title_fills,
        "maskFills": mask_fills,
        "titleGen": raw_data.get('title_gen', 2),  # 假设默认值为2
        "maskGen": raw_data.get('mask_gen', 2),  # 假设默认值为2
        "conversionComponentTypes": raw_data.get('conversionComponentTypes', []),
        "qualInfo": {
            "applyId": raw_data.get('qualInfo', {}).get('applyId', '')
        },
        "pageEnterTime": 1752200618249,  # 固定值
        "pageSubmitTime": 1752201022212  # 固定值
    }

    return transformed_data



def get_mask_fill_detail(creative_id, account_id, unit_dict_cookie, note_id, mask_fill_status):
    material_url = "https://ad.xiaohongshu.com/api/leona/rtb/prefer/material/info"

    """
    获取指定创意ID的封面信息
    """
    headers['v-seller-id'] = account_id

    data = {
        "noteId": note_id,
        "creativityId": creative_id
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(material_url, headers=headers, cookies=unit_dict_cookie, data=data)

    if response.status_code == 200:
        raw_data = response.json().get('data', {})
        mask_info_detail = transform_data(raw_data, mask_fill_status)
        return mask_info_detail
    return {}

def get_final_construct_edit_data(creative_id, account_id, unit_dict_cookie, note_id, mask_fill_status):
    mask_info_detail = get_mask_fill_detail(creative_id, account_id, unit_dict_cookie, note_id, mask_fill_status)

    creative_url = "https://ad.xiaohongshu.com/api/leona/rtb/creativity/get"

    """
    获取指定创意ID的所有创意信息
    """
    headers['v-seller-id'] = account_id

    params = {
        "id": creative_id
    }
    response = requests.get(creative_url, headers=headers, cookies=unit_dict_cookie, params=params)

    if response.status_code == 200:
        raw_data = response.json().get('data', {})
        final_construct_edit_data = construct_edit_data(raw_data, mask_info_detail['titleFills'], mask_info_detail['maskFills'])

        return final_construct_edit_data
    return {}

def edit_creative(final_construct_edit_data, account_id, unit_dict_cookie):
    url = "https://ad.xiaohongshu.com/api/leona/rtb/creativity/update"
    data = final_construct_edit_data

    headers['v-seller-id'] = account_id

    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url, headers=headers, cookies=unit_dict_cookie, data=data)
    return response.json()



# mask_info_detail_data = get_mask_fill_detail("1783799772", "66da9a60a6e9d100165983cc", material_cookies, "68086343000000000903a999")
# raw_data_1 = get_final_construct_edit_data("1783799772", "66da9a60a6e9d100165983cc", material_cookies, "68086343000000000903a999", "开启")
# response = edit_creative(raw_data_1, "66da9a60a6e9d100165983cc", material_cookies)
# res = response.json()
# print(res)